<template>
  <div class="approval-management-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="nav-content">
        <div class="nav-left">
          <h1 class="nav-title">
            <span class="title-icon">✅</span>
            采购订单审批管理
          </h1>
        </div>
        <div class="nav-right">
          <div class="system-status">
            <div class="status-item">
              <span class="status-label">待审批</span>
              <span class="status-value pending">{{ statistics.pending }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">今日已审批</span>
              <span class="status-value">{{ statistics.todayApproved }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">审批用时(平均)</span>
              <span class="status-value">{{ statistics.avgProcessTime }}分钟</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 快速统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card urgent">
          <div class="stat-icon">🚨</div>
          <div class="stat-content">
            <div class="stat-title">紧急审批</div>
            <div class="stat-value">{{ statistics.urgent }}</div>
            <div class="stat-desc">超过1天未处理</div>
          </div>
        </div>
        <div class="stat-card high">
          <div class="stat-icon">⚡</div>
          <div class="stat-content">
            <div class="stat-title">高优先级</div>
            <div class="stat-value">{{ statistics.highPriority }}</div>
            <div class="stat-desc">需优先处理</div>
          </div>
        </div>
        <div class="stat-card large">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-title">大额订单</div>
            <div class="stat-value">{{ statistics.largeAmount }}</div>
            <div class="stat-desc">>10万元</div>
          </div>
        </div>
        <div class="stat-card normal">
          <div class="stat-icon">📋</div>
          <div class="stat-content">
            <div class="stat-title">普通审批</div>
            <div class="stat-value">{{ statistics.normal }}</div>
            <div class="stat-desc">常规订单</div>
          </div>
        </div>
      </div>

      <!-- 操作工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button 
            type="success" 
            :disabled="selectedOrders.length === 0"
            @click="batchApprove"
          >
            批量审批 ({{ selectedOrders.length }})
          </el-button>
          <el-button 
            type="danger" 
            :disabled="selectedOrders.length === 0"
            @click="batchReject"
          >
            批量拒绝 ({{ selectedOrders.length }})
          </el-button>
          <el-button icon="Refresh" @click="refreshData">刷新</el-button>
        </div>
        <div class="toolbar-right">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索订单号、供应商..."
            style="width: 250px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filters">
        <el-form :model="queryParams" inline>
          <el-form-item label="审批状态">
            <el-select v-model="queryParams.status" placeholder="选择状态" clearable style="width: 150px">
              <el-option label="待审批" value="待审批" />
              <el-option label="审批中" value="审批中" />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select v-model="queryParams.priority" placeholder="选择优先级" clearable style="width: 120px">
              <el-option label="紧急" value="紧急" />
              <el-option label="高" value="高" />
              <el-option label="中" value="中" />
              <el-option label="低" value="低" />
            </el-select>
          </el-form-item>
          <el-form-item label="金额范围">
            <el-select v-model="queryParams.amountRange" placeholder="选择金额范围" clearable style="width: 150px">
              <el-option label="<1万" value="small" />
              <el-option label="1-10万" value="medium" />
              <el-option label="10-50万" value="large" />
              <el-option label=">50万" value="huge" />
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="pendingOrders"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :row-class-name="getRowClassName"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="紧急程度" width="100">
            <template #default="{ row }">
              <div class="urgency-indicator">
                <span v-if="isUrgent(row)" class="urgency-badge urgent">🚨</span>
                <span v-else-if="isHighPriority(row)" class="urgency-badge high">⚡</span>
                <span v-else-if="isLargeAmount(row)" class="urgency-badge large">💰</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="orderNumber" label="订单号" width="160" fixed="left">
            <template #default="{ row }">
              <el-link type="primary" @click="viewDetail(row.id)">
                {{ row.orderNumber }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" label="供应商" width="200" />
          <el-table-column prop="orderType" label="订单类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getOrderTypeTagType(row.orderType)">
                {{ row.orderType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriorityTagType(row.priority)" size="small">
                {{ row.priority }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="订单金额" width="120" align="right">
            <template #default="{ row }">
              <span :class="['amount', { 'large-amount': row.totalAmount > 100000 }]">
                ¥{{ formatCurrency(row.totalAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="申请人" width="120" />
          <el-table-column label="提交时间" width="140">
            <template #default="{ row }">
              <div class="submit-time">
                <div>{{ formatDate(row.submitTime) }}</div>
                <div class="time-elapsed" :class="getElapsedTimeClass(row.submitTime)">
                  {{ getElapsedTime(row.submitTime) }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="expectedDeliveryDate" label="期望交货" width="120">
            <template #default="{ row }">
              {{ formatDate(row.expectedDeliveryDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click="viewDetail(row.id)">
                  详情
                </el-button>
                <el-button size="small" type="success" @click="quickApprove(row)">
                  审批
                </el-button>
                <el-button size="small" type="danger" @click="quickReject(row)">
                  拒绝
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageIndex"
          v-model:page-size="queryParams.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialog.visible"
      :title="approvalDialog.isBatch ? '批量审批' : '审批采购订单'"
      width="600px"
      @close="closeApprovalDialog"
    >
      <div v-if="approvalDialog.isBatch" class="batch-info">
        <el-alert
          :title="`即将${approvalDialog.decision === '通过' ? '批准' : '拒绝'}${approvalDialog.orders.length}个采购订单`"
          :type="approvalDialog.decision === '通过' ? 'success' : 'warning'"
          show-icon
          :closable="false"
        />
        <div class="batch-orders">
          <el-tag 
            v-for="order in approvalDialog.orders" 
            :key="order.id"
            class="order-tag"
          >
            {{ order.orderNumber }}
          </el-tag>
        </div>
      </div>
      
      <el-form :model="approvalDialog.form" label-width="80px">
        <el-form-item v-if="!approvalDialog.isBatch" label="审批决定">
          <el-radio-group v-model="approvalDialog.form.decision">
            <el-radio value="通过">同意</el-radio>
                          <el-radio value="驳回">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalDialog.form.comments"
            type="textarea"
            :rows="4"
            :placeholder="approvalDialog.isBatch ? '批量审批意见...' : '请输入审批意见...'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeApprovalDialog">取消</el-button>
          <el-button 
            :type="approvalDialog.decision === '通过' ? 'success' : 'danger'" 
            @click="submitApproval" 
            :loading="submitting"
          >
            确认{{ approvalDialog.decision === '通过' ? '批准' : '拒绝' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { usePurchaseOrderStore } from '@/stores/purchaseOrder'
import type { PurchaseOrderDto, PurchaseOrderQueryDto, ApprovalDecisionDto } from '@/types/console'

// 路由
const router = useRouter()

// 状态管理
const purchaseOrderStore = usePurchaseOrderStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const selectedOrders = ref<PurchaseOrderDto[]>([])
const dateRange = ref<[string, string]>(['', ''])

// 查询参数
const queryParams = ref<PurchaseOrderQueryDto>({
  pageIndex: 1,
  pageSize: 20,
  keyword: '',
  status: '待审批',
  priority: '',
  amountRange: ''
})

// 审批对话框
const approvalDialog = reactive({
  visible: false,
  isBatch: false,
  decision: '通过',
  orders: [] as PurchaseOrderDto[],
  form: {
    decision: '通过',
    comments: ''
  }
})

// 统计数据
const statistics = ref({
  pending: 0,
  todayApproved: 0,
  avgProcessTime: 0,
  urgent: 0,
  highPriority: 0,
  largeAmount: 0,
  normal: 0
})

// 计算属性
const pendingOrders = computed(() => purchaseOrderStore.purchaseOrders)
const pagination = computed(() => purchaseOrderStore.pagination)

// 生命周期
onMounted(() => {
  loadData()
  loadStatistics()
})

// 监听查询参数变化
watch(
  () => [queryParams.value.status, queryParams.value.priority, queryParams.value.amountRange],
  () => {
    handleSearch()
  }
)

// 方法
const loadData = async () => {
  loading.value = true
  try {
    await purchaseOrderStore.fetchPurchaseOrders(queryParams.value)
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    // 模拟加载统计数据
    statistics.value = {
      pending: 25,
      todayApproved: 12,
      avgProcessTime: 15,
      urgent: 3,
      highPriority: 8,
      largeAmount: 5,
      normal: 9
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const handleSearch = () => {
  queryParams.value.pageIndex = 1
  loadData()
}

const handleDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    queryParams.value.createStartTime = dates[0]
    queryParams.value.createEndTime = dates[1]
  } else {
    queryParams.value.createStartTime = undefined
    queryParams.value.createEndTime = undefined
  }
  handleSearch()
}

const resetFilters = () => {
  queryParams.value = {
    pageIndex: 1,
    pageSize: 20,
    keyword: '',
    status: '待审批',
    priority: '',
    amountRange: ''
  }
  dateRange.value = ['', '']
  loadData()
}

const refreshData = () => {
  loadData()
  loadStatistics()
}

const handleSizeChange = (size: number) => {
  queryParams.value.pageSize = size
  loadData()
}

const handleCurrentChange = (page: number) => {
  queryParams.value.pageIndex = page
  loadData()
}

const handleSelectionChange = (selection: PurchaseOrderDto[]) => {
  selectedOrders.value = selection
}

// 快速判断方法
const isUrgent = (order: PurchaseOrderDto) => {
  if (!order.submitTime) return false
  const submitDate = new Date(order.submitTime)
  const now = new Date()
  const diffHours = (now.getTime() - submitDate.getTime()) / (1000 * 60 * 60)
  return diffHours > 24
}

const isHighPriority = (order: PurchaseOrderDto) => {
  return ['紧急', '高'].includes(order.priority || '')
}

const isLargeAmount = (order: PurchaseOrderDto) => {
  return (order.totalAmount || 0) > 100000
}

// 表格行样式
const getRowClassName = ({ row }: { row: PurchaseOrderDto }) => {
  if (isUrgent(row)) return 'urgent-row'
  if (isHighPriority(row)) return 'high-priority-row'
  if (isLargeAmount(row)) return 'large-amount-row'
  return ''
}

// 审批操作
const viewDetail = (id: number) => {
  router.push(`/main/procurement/purchase-order/${id}`)
}

const quickApprove = (order: PurchaseOrderDto) => {
  showApprovalDialog([order], '通过')
}

const quickReject = (order: PurchaseOrderDto) => {
  showApprovalDialog([order], '驳回')
}

const batchApprove = () => {
  if (selectedOrders.value.length === 0) return
  showApprovalDialog(selectedOrders.value, '通过', true)
}

const batchReject = () => {
  if (selectedOrders.value.length === 0) return
  showApprovalDialog(selectedOrders.value, '驳回', true)
}

const showApprovalDialog = (orders: PurchaseOrderDto[], decision: string, isBatch = false) => {
  approvalDialog.visible = true
  approvalDialog.isBatch = isBatch
  approvalDialog.decision = decision
  approvalDialog.orders = orders
  approvalDialog.form = {
    decision: decision,
    comments: ''
  }
}

const closeApprovalDialog = () => {
  approvalDialog.visible = false
  approvalDialog.isBatch = false
  approvalDialog.orders = []
  approvalDialog.form = {
    decision: '通过',
    comments: ''
  }
}

const submitApproval = async () => {
  submitting.value = true
  try {
    const decision: ApprovalDecisionDto = {
      decision: approvalDialog.form.decision,
      comments: approvalDialog.form.comments,
      attachmentUrls: []
    }
    
    if (approvalDialog.isBatch) {
      // 批量审批
      const promises = approvalDialog.orders.map(order => 
        purchaseOrderStore.approveOrder(order.id, decision)
      )
      await Promise.all(promises)
      ElMessage.success(`批量${decision.decision === '通过' ? '批准' : '拒绝'}成功`)
    } else {
      // 单个审批
      await purchaseOrderStore.approveOrder(approvalDialog.orders[0].id, decision)
      ElMessage.success(`${decision.decision === '通过' ? '批准' : '拒绝'}成功`)
    }
    
    closeApprovalDialog()
    selectedOrders.value = []
    loadData()
    loadStatistics()
  } catch (error) {
    ElMessage.error('审批失败')
  } finally {
    submitting.value = false
  }
}

// 工具方法
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatCurrency = (amount: number) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const getElapsedTime = (submitTime: string) => {
  if (!submitTime) return ''
  const submitDate = new Date(submitTime)
  const now = new Date()
  const diffMs = now.getTime() - submitDate.getTime()
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffHours / 24)
  
  if (diffDays > 0) {
    return `${diffDays}天前`
  } else if (diffHours > 0) {
    return `${diffHours}小时前`
  } else {
    const diffMinutes = Math.floor(diffMs / (1000 * 60))
    return `${diffMinutes}分钟前`
  }
}

const getElapsedTimeClass = (submitTime: string) => {
  if (!submitTime) return ''
  const submitDate = new Date(submitTime)
  const now = new Date()
  const diffHours = (now.getTime() - submitDate.getTime()) / (1000 * 60 * 60)
  
  if (diffHours > 24) return 'urgent'
  if (diffHours > 8) return 'warning'
  return 'normal'
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    '待审批': 'warning',
    '审批中': 'primary',
    '已审批': 'success',
    '已拒绝': 'danger'
  }
  return typeMap[status] || 'info'
}

const getOrderTypeTagType = (orderType: string) => {
  const typeMap: Record<string, string> = {
    '标准采购': '',
    '紧急采购': 'danger',
    '框架采购': 'success',
    '补充采购': 'warning'
  }
  return typeMap[orderType] || ''
}

const getPriorityTagType = (priority: string) => {
  const typeMap: Record<string, string> = {
    '低': 'info',
    '中': '',
    '高': 'warning',
    '紧急': 'danger'
  }
  return typeMap[priority] || ''
}
</script>

<style scoped>
.approval-management-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.top-navbar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-left .nav-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.title-icon {
  font-size: 1.8rem;
}

.nav-right .system-status {
  display: flex;
  gap: 2rem;
}

.status-item {
  text-align: center;
}

.status-label {
  display: block;
  font-size: 0.75rem;
  color: #666;
  margin-bottom: 0.25rem;
}

.status-value {
  display: block;
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
}

.status-value.pending {
  color: #e6a23c;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 2rem;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.urgent {
  border-left: 4px solid #f56c6c;
}

.stat-card.high {
  border-left: 4px solid #e6a23c;
}

.stat-card.large {
  border-left: 4px solid #67c23a;
}

.stat-card.normal {
  border-left: 4px solid #409eff;
}

.stat-icon {
  font-size: 2rem;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 0.25rem;
}

.stat-value {
  font-size: 2rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 0.25rem;
}

.stat-desc {
  font-size: 0.75rem;
  color: #999;
}

.toolbar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1rem;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 0.5rem;
}

.toolbar-right {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.filters {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1rem;
  margin-bottom: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.table-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1rem;
  margin-bottom: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.urgency-indicator {
  display: flex;
  justify-content: center;
}

.urgency-badge {
  font-size: 1.2rem;
  padding: 0.25rem;
  border-radius: 4px;
}

.urgency-badge.urgent {
  background: #fef0f0;
  color: #f56c6c;
}

.urgency-badge.high {
  background: #fdf6ec;
  color: #e6a23c;
}

.urgency-badge.large {
  background: #f0f9ff;
  color: #67c23a;
}

.submit-time {
  text-align: center;
}

.time-elapsed {
  font-size: 0.75rem;
  padding: 0.125rem 0.25rem;
  border-radius: 4px;
  margin-top: 0.25rem;
}

.time-elapsed.normal {
  background: #f0f9ff;
  color: #409eff;
}

.time-elapsed.warning {
  background: #fdf6ec;
  color: #e6a23c;
}

.time-elapsed.urgent {
  background: #fef0f0;
  color: #f56c6c;
}

.amount {
  font-weight: 600;
}

.amount.large-amount {
  color: #e6a23c;
}

.action-buttons {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

/* 表格行样式 */
:deep(.urgent-row) {
  background-color: #fef0f0 !important;
}

:deep(.high-priority-row) {
  background-color: #fdf6ec !important;
}

:deep(.large-amount-row) {
  background-color: #f0f9ff !important;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.batch-info {
  margin-bottom: 1rem;
}

.batch-orders {
  margin-top: 1rem;
  max-height: 200px;
  overflow-y: auto;
}

.order-tag {
  margin: 0.25rem;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-content {
    padding: 1rem;
    flex-direction: column;
    gap: 1rem;
  }

  .main-content {
    padding: 1rem;
  }

  .toolbar {
    flex-direction: column;
    gap: 1rem;
  }

  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: center;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style> 